import React, { Component } from 'react'
import {Card,Button, Checkbox, Form, Input,message} from 'antd'
import styles from'./index.module.scss'
import logo from 'assets/logo.png'
import {login} from 'api/user'
import {setToken} from 'utils/storage'

export default class Login extends Component {
  render() {
    return (
      <div className={styles.login}>
        <Card className='login-container'>
          <img src={logo} alt="" className='login-logo'></img>
          {/* 表单 */}
           <Form
      onFinish={this.onFinish}
      // onFinishFailed={onFinishFailed}
      initialValues={{
        mobile:'13911111111',
        code:'246810',
        agree:true
      }}
      size='large'
    >
      <Form.Item
        name="mobile"
        rules={[
          {
            required: true,
            message: '手机号不能为空!',
          },{
            pattern:/^1[3-9]\d{9}$/,
            message: '手机号格式错误!'
          }
        ]}
      >
        <Input placeholder='请输入手机号' autoComplete='off' />
      </Form.Item>

      <Form.Item
        name="code"
        rules={[
          {
            required: true,
            message: '验证码不能为空!',
          },{
            pattern:/^\d{6}$/,
            message: '验证码格式错误!'
          }
        ]}
      >
        <Input placeholder='请输入验证码' autoComplete='off'/>
      </Form.Item>

      <Form.Item
        name="agree"
        valuePropName="checked"
        rules={[
          {
          //  自定义校验
          validator(rule,value){
            if(value)return Promise.resolve()
            return Promise.reject(new Error('请阅读并同意《隐私条款》和《用户协议》!'))
          }
          }
        ]}
      >
        <Checkbox>我已阅读并同意《隐私条款》和《用户协议》</Checkbox>
      </Form.Item>

      <Form.Item
      >
        <Button type="primary" htmlType="submit" block>
          登录
        </Button>
      </Form.Item>
    </Form>
        </Card>
      </div>
    )
  }
  // 登录
  onFinish= async({mobile,code})=>{
    try{
    const res = await login(mobile,code)
    setToken(res.data.token)
    const {state} =this.props.location
    if (state){
      this.props.history.push(state.from)
    }else{
    this.props.history.push('/home')
    }
    }catch(error){
      message.warning(error.response.data.message,1)
    }
  }
}
